/**
 * 渠道发布弹框
 * releaseStatus 渠道发布状态（0=未发布 1=已发布 2=待审核 3=已下线）
 *
 */
import React from 'react';
import { TreeSelect } from 'antd';

const releaseTag = {
    0: <span style={{ marginLeft: 8 }}>[未发布]</span>,
    1: <span style={{ marginLeft: 8 }}>[已发布]</span>,
    2: <span style={{ marginLeft: 8 }}>[待审核]</span>,
    3: <span style={{ marginLeft: 8 }}>[已下线]</span>
};

export default function SelectChannel(props) {
    const { data = [], onChange = () => {}, loading, mode, type, ...rest } = props;

    const children = data.map(item => {
        const { accountDetailVOList = [], accountAuthVOList = [], releaseStatus } = item;
        const accountReleaseStatus = accountDetailVOList.map(account => account.releaseStatus);
        const finalReleaseStatus = accountDetailVOList.length === 0 ? [releaseStatus] : accountReleaseStatus;

        const disabledMap = {
            release: finalReleaseStatus.some(status => ![0].includes(status)),
            update: finalReleaseStatus.some(status => status !== 1),
            online: finalReleaseStatus.some(status => status !== 3),
            offline: finalReleaseStatus.some(status => status !== 1)
        };

        // 招聘网站没有账号时禁用
        const noAccount = accountAuthVOList.length === 0;

        return {
            title: (
                <div>
                    {item.channelName}
                    {releaseTag[item.releaseStatus]}
                    {item.channelStatus === 0 && '[已禁用]'}
                    {noAccount && '[未授权]'}
                </div>
            ),
            disabled: item.channelStatus === 0 || noAccount || disabledMap[mode],
            value: item.channelCode,
            key: item.channelCode
        };
    });

    const defaultValue = React.useMemo(() => {
        if (data.length === 0 || loading) {
            return [];
        }
        return children.filter(item => !item.disabled).map(item => item.value);
    }, [data, loading]);

    const disabled = children.every(item => item.disabled);
    const treeData = [
        {
            title: '全部',
            disabled,
            value: 'all',
            key: 'all',
            children
        }
    ];

    React.useEffect(() => {
        onChange(defaultValue);
    }, [defaultValue]);

    if (loading) {
        return null;
    }

    return (
        <TreeSelect
            defaultValue={defaultValue}
            placeholder="请选择"
            treeDefaultExpandAll
            maxTagCount={1}
            treeData={treeData}
            style={{ width: 300 }}
            onChange={value => {
                if (value.includes('all')) {
                    onChange(children.filter(item => !item.disabled).map(item => item.value));
                } else {
                    onChange(value);
                }
            }}
            showCheckedStrategy={TreeSelect.SHOW_PARENT}
            {...rest}
        />
    );
}
